package com.tuanchau.android.englishtooltip.service;

import java.util.Locale;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;

import com.tuanchau.android.englishtooltip.Global;

public class SpeechService extends Service implements OnInitListener {

	private TextToSpeech tts;
	private SharedPreferences pref;

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);

		if (tts == null) {
			tts = new TextToSpeech(getApplicationContext(), this);
		}
		else {
			doSpeak();
		}
	}

	@Override
	public IBinder onBind(Intent intent) {

		return null;
	}

	@Override
	public void onInit(int status) {
		if (status == TextToSpeech.SUCCESS) {

			int result = tts.setLanguage(Locale.US);
			if (result == TextToSpeech.LANG_MISSING_DATA
					|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
			} else {
				doSpeak();
			}
		}
	}

	private void doSpeak() {
		Context context = getApplicationContext();
		if(pref == null) {
			pref = context.getSharedPreferences(Global.PREF_FILE_NAME, Context.MODE_PRIVATE);
		}
		
		if (tts == null) {
			tts = new TextToSpeech(context, this);
		}
		AudioManager am = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);
		int volume = pref.getInt(Global.PREF_KEY_VOLUME, 8);
		am.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);

		String word = pref.getString(Global.PREF_KEY_CURRENT_WORD, "");
		tts.speak(word, TextToSpeech.QUEUE_FLUSH, null);
	}

}
